import os
import openpyxl
import re

from dateutil import parser
from datetime import datetime, timedelta
from Tool.PathBuilder import PathBuilder


class Comparison:
    def __init__(self):
        self.pathReader = PathBuilder('Tool')
        self.path = self.pathReader.joinFullPath('bugList')
        self.bugRecordsPath = self.pathReader.joinFullPath('bugList', 'BugRecords.xlsx')

    # 废弃 未使用
    def _getTargetFile(self):
        """
        :return: 获取文件开头为 TapdBugList 的文件合集
        """
        fileNames = os.listdir(self.path)
        # 过滤出以 "TapdBugList" 开头的文件
        tapdBugFiles = [fileName for fileName in fileNames if fileName.startswith("TapdBugList")]

        return tapdBugFiles

    # 废弃 未使用
    def _getOldList(self):
        """
        :return: 读取上一份导入的bug的数据
        """
        timeStrLists = []
        if not self._getTargetFile():
            return []
        else:
            fileLists = self._getTargetFile()
            pattern = r"\[(.*?)\]"
            for fileName in fileLists:
                match = re.search(pattern, fileName)
                # 将文件名的时间替换成正常的时间（字符串格式）用作对比哪个是最新的值
                timeStrLists.append(str(match.group(1)).replace('.', ':'))

            # 将日期字符串转换为日期对象
            dates = [parser.parse(timeStr) for timeStr in timeStrLists]
            maxDateIndex = dates.index(max(dates))
            # 获取最大值的文件名
            targetFileName = fileLists[maxDateIndex]
            targetPath = self.pathReader.joinFullPath('bugList', targetFileName)

            # 3. 打开文件 获取所有数据
            dataList = []

            workbook = openpyxl.load_workbook(targetPath)
            worksheet = workbook.worksheets[0]

            for row in worksheet.iter_rows(min_row=2, values_only=True):
                bugDict = {}
                for col, value in enumerate(row, start=1):
                    key = worksheet.cell(1, col).value  # 假设第一行是键
                    bugDict[key] = value
                dataList.append(bugDict)

            return dataList

    def _getAllBugRecords(self):
        """
        获取[BugRecords.xlsx]的数据
        :return: 一周内的所有bug的数据 用于判断是否为重打开的bug
        """
        recordLists = []
        recordDict = {}
        # 打开BugRecords
        workbook = openpyxl.load_workbook(self.bugRecordsPath)
        # sheet = workbook.active
        worksheet = workbook.worksheets[0]

        # 遍历工作表中的所有单元格
        for row in worksheet.iter_rows(min_row=2, values_only=True):
            for col, value in enumerate(row, start=1):
                key = worksheet.cell(1, col).value
                recordDict[key] = value
            if all(value is not None for value in recordDict.values()):
                recordLists.append(recordDict)

        return recordLists

    def _getNotOverdueRecords(self, overdue):
        """

        :param overdue: 过期时间
        :return: 过滤未移除的数据
        """
        # 移除超过处理时间的BugList
        # 扫描bug 如果当前时间 >= bug创建时间 + n小时（做成参数overdue） 直接remove这条数据
        recordIndex = []
        # overdueTime = None
        records = self._getAllBugRecords()
        if records is None or overdue is None:
            return records
        else:
            for index, record in enumerate(records):
                if record['createTime'] is not None:
                    dateResult = datetime.strptime(record['createTime'], '%Y/%m/%d %H:%M') + timedelta(hours=int(overdue))
                    overdueTime = dateResult.strftime('%Y/%m/%d %H:%M')
                else:
                    break

                currentTime = str(datetime.now().strftime('%Y/%m/%d %H:%M'))

                if currentTime >= overdueTime:
                    recordIndex.append(index)

            for index in sorted(recordIndex, reverse=True):
                # print(f'Delete stale data {records[index]}')
                del records[index]

            return records

    def _setBugRecords(self, bugRecords):
        """
        :param bugRecords: 新增的未存在于bugRecords中的bug
        :return: 所有导入过的bug
        """

        workbook = openpyxl.load_workbook(self.bugRecordsPath)
        sheet = workbook.active

        # 获取表头所在的行
        headersRow = 1  # 表头所在的行数
        headersMap = {}  # 存储表头的字典
        for col in range(1, sheet.max_column + 1):
            header = sheet.cell(row=headersRow, column=col).value
            if header:
                headersMap[header] = col
            else:
                break

        # 写入数值
        for col, (key, value) in enumerate(bugRecords.items(), start=1):
            if key in headersMap:
                col = headersMap[key]
                sheet.cell(row=sheet.max_row, column=col, value=value)

        # 保存更改
        workbook.save(self.bugRecordsPath)

    def getFinalBugList(self, newBugList, overtime, overdue):
        """
        :param newBugList: 新生成的bugList的数据集
        :param overtime: 对比旧bugList的创建时间，超过多少小时加入到最终的bugList中
        :param overdue: bugRecords数据的过期时间
        :return: 最终生成excel的数据集
        """
        resultList = []

        # 读取的是所有的bugRecords
        bugRecords = self._getAllBugRecords()
        # 读取的是未逾期的bugRecords
        bugNotOverdueRecord = self._getNotOverdueRecords(overdue)

        if not bugRecords and not bugNotOverdueRecord:
            # 第一次为空 把第一次的bugList添加到bugRecords中
            for bugList in newBugList:
                self._setBugRecords(bugList)
            return newBugList
        else:
            if overtime is not None:
                # 循环比对数据，有存在的剔除，不存在的加入列表
                for bugList in newBugList:
                    # 新增一个时间对比 创建日期+24小时>当前时间 存在也要添加入list中
                    currentTime = str(datetime.now().strftime('%Y/%m/%d %H:%M'))
                    confirmTime = (datetime.strptime(bugList['createTime'], '%Y/%m/%d %H:%M') + timedelta(
                        hours=int(overtime))).strftime('%Y/%m/%d %H:%M')

                    # 如果 当前时间 >= bug创建时间 + 24小时 或者 这个bug不在之前的bugList中
                    for bugRecord in bugRecords:
                        # 不存在于 BugRecords, 添加到结果集后，也要添加到 BugRecords
                        if bugList['title'] != bugRecord['title']:
                            resultList.append(bugList)
                            self._setBugRecords(bugList)
                        elif bugList['title'] == bugRecord['title'] and currentTime >= confirmTime:
                            resultList.append(bugList)
                return newBugList
            else:
                return newBugList
